//jQuery 
$(document).ready(function () {
    protobuf.load(proto_files, function (err, root) {
        proto_root = root
        console.log("index", proto_root)
    });
    document.getElementById("fileInput").addEventListener("change", fileInputWorker_index);
})

function fileInputWorker_index(event) {
    index = null
    file_list = {}
    const files = event.target.files;
    console.log("eeee 获取文件长度" + files.length);
    if (!files) {
        console.error("No file selected.");
        return;
    }
    file_list["index"] = []
    file_list['avp'] = null
    for (var i = 0; i < files.length; ++i) {
        const f = files[i];
        var file_name = f.name.split(".")
        var app = file_name[file_name.length - 1]
        console.log("eeee app=" + app);
        if (app == "avp") {
            file_list['avp'] = f
            console.log("eeee 111 avp" + file_list)
        } else if (app == "index") {
            file_list["index"].push(f)
            console.log("eeee 222 index" + file_list["index"])
        } else if (app == "sem" || app == "loc" || app == "nav" || app == "rec" || app == "occ") {
            var id = f.name.split(".")[0]
            console.log("eeee 333 else id=" + id)
            if (file_list[id]) {
                file_list[id].push(f)
            } else {
                file_list[id] = [f]
            }
            console.log("eeee 444 else other app=" + file_list[id])
        }
    }

    var index = null
    var len = file_list["index"].length
    // index 界面加载的.index文件
    if (file_list["avp"]) index = file_list["avp"]
    else if (len > 0) {
        file_list["index"].sort()
        index = file_list["index"][len - 1]
    }

    console.log('eeee ndex file : ', index)
    //解析proto文件
    const reader = new FileReader();
    var app = index.name.split(".")[1]
    console.log("eeee event.target.result=" + event.target.result);
    if (app == "avp" || app == "index") {
        reader.onload = function (event) { parse_avp_pb(event.target.result); };
    }
    reader.readAsArrayBuffer(index);
}

function clear_index_show() {
    utm_map.eachLayer((obj) => {
        obj.remove()
    })
    L.tileLayer('http://wprd04.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}', { minZoom: 3 }).addTo(utm_map)
    utm_entrance_map = L.featureGroup().addTo(utm_map)
}

//解析proto文件
function parse_avp_pb(buffer) {
    const YourMessage = proto_root.lookupType(proto_type["avp"]["mes"]);
    const message = YourMessage.decode(new Uint8Array(buffer));
    console.log("eeee 展示列表控件 message=" + message)
    clear_index_show()
    // 展示列表
    var divContainer = document.getElementById("index_tables")
    while (divContainer.firstChild) {
        divContainer.removeChild(divContainer.firstChild);
    }

    index = new Index(message)
    console.log("eeee message index =" + index)
    index.RenderIndexTable(divContainer)
    index.setFromRemote(false)
    index_from_remote = false
}